package com.cloudspace.yunloan.manager;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;


import com.cloudspace.photopicker.PhotoPickerActivity;
import com.cloudspace.photopicker.utils.PhotoPickerIntent;
import com.cloudspace.yunloan.R;
import com.cloudspace.yunloan.activity.YunloanBaseActivity;
import com.cloudspace.yunloan.utils.ActionSheet;
import com.cloudspace.yunloan.utils.BitmapUtil;
import com.cloudspace.yunloan.utils.MMAlert;
import com.cloudspace.yunloan.utils.PictureActivityUtil;
import com.cloudspace.yunloan.utils.SDCardSizeUtil;
import com.cloudspace.yunloan.utils.ToastMaker;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

public class HeadphotoManager {
    private YunloanBaseActivity mActivity;

    private static final int REQUEST_CAMERA = 200;
    private static final int REQUEST_STORAGE = 201;
    private static final int REQUEST_CANMERA_STORAGE = 202;

    private static final int HEADPHOTO = 1001;
    private static final int HEADPHOTO_PICKED_FROM_GALLERY = 1002;
    private File tempFile = null;

    public HeadphotoManager(YunloanBaseActivity activity) {
        this.mActivity = activity;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                // 拍照返回的数据
                case HEADPHOTO:
                    String paths = PictureActivityUtil.getNoCropPath(mActivity, data);
                    if (paths != null) {
                        compressPicture(paths);
                    }
                    break;
                //裁剪返回的数据
                case HEADPHOTO + PictureActivityUtil.PHOTO_CROP: {//新上传了头像
                    getHeadphotoFromCrop(data);
                }
                break;
                //从相册 选取照片返回的数据，结果将先到TakePhotoActivity处理方向之后完成上传，再通知该界面更新
                case HEADPHOTO_PICKED_FROM_GALLERY:
                    List<String> photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    if (photos.size() == 1) {
                        compressPicture(photos.get(0));
                    }
                    break;
                case HEADPHOTO_PICKED_FROM_GALLERY + PictureActivityUtil.PHOTO_CROP: {
                    getHeadphotoFromCrop(data);
                }
                break;
            }
        }
    }

    private void compressPicture(String path) {
        Bitmap bm = BitmapFactory.decodeFile(path);

        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
            bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);


            if (mOnHeadphotoCropListener != null){
                mOnHeadphotoCropListener.headphotoCroped(new File(path));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA: {
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        if (mActivity.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, REQUEST_CANMERA_STORAGE)) {
                            getHeadPhotoFromCamera();
                        }
                    } else {
                        ToastMaker.showToastShort(R.string.permission_camera_error);
                    }
                }
                break;
            }
            case REQUEST_CANMERA_STORAGE: {
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        getHeadPhotoFromCamera();
                    } else {
                        ToastMaker.showToastShort(R.string.permission_storage_error);
                    }
                }
                break;
            }
            case REQUEST_STORAGE: {
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        getHeadPhotoFromStorage();
                    } else {
                        ToastMaker.showToastShort(R.string.permission_storage_error);
                    }
                }
                break;
            }
        }
    }

    public void getHeadphotoFromCrop(Intent data) {
        tempFile = new File(PictureActivityUtil.getCropPath(data));
        if (tempFile != null && tempFile.exists()) {
            if (mOnHeadphotoCropListener != null) {
                mOnHeadphotoCropListener.headphotoCroped(tempFile);
            }
        } else {
            ToastMaker.showToastShort("图片裁减异常");
        }
    }

    public void showChangeHeadPhotoDialog() {
//        MMAlert.showAlert(mActivity, mActivity.getResources().getStringArray(R.array.photo_up_flag), new ActionSheet.SimpleActionSheetListener() {
//            @Override
//            public void onItemClick(ActionSheet actionSheet, int index) {
//                switch (index) {
//                    case 0:
//                        changeHeadphotoClick4Camera();
//                        break;
//                    case 1:
//                        changeHeadphotoClick4Storage();
//                        break;
//                }
//            }
//        });

        changeHeadphotoClick4Camera();
    }

    public void changeHeadphotoClick4Camera() {
        if (mActivity.hasPermission(Manifest.permission.CAMERA) && mActivity.hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            getHeadPhotoFromCamera();
        } else {
            if (mActivity.checkPermission(Manifest.permission.CAMERA, REQUEST_CAMERA)) {
                mActivity.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, REQUEST_CANMERA_STORAGE);
            }
        }
    }

    public void changeHeadphotoClick4Storage() {
        if (mActivity.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, REQUEST_STORAGE)) {
            getHeadPhotoFromStorage();
        }
    }


    private void getHeadPhotoFromCamera() {
        if (SDCardSizeUtil.isSdCardExist()) {// 判断是否有SD卡
            if (mCameraCallback != null) {
                mCameraCallback.cameraClicked();
            }
            PictureActivityUtil.doTakePhoto(mActivity, HEADPHOTO);// 用户点击了从照相机获取
        }
    }


    private void getHeadPhotoFromStorage() {
        PhotoPickerIntent intent = new PhotoPickerIntent(mActivity);
        intent.setPhotoCount(1);
        intent.setTitle(mActivity.getString(R.string.camera_roll));
        intent.setShowCamera(false);
        mActivity.startActivityForResult(intent, HEADPHOTO_PICKED_FROM_GALLERY);
    }


    private OnHeadphotoCropListener mOnHeadphotoCropListener;

    public void setOnHeadphotoCropListener(OnHeadphotoCropListener onHeadphotoCropListener) {
        this.mOnHeadphotoCropListener = onHeadphotoCropListener;
    }

    public interface OnHeadphotoCropListener {
        void headphotoCroped(File file);
    }


    private CameraCallback mCameraCallback;

    public void addCameraCallback(CameraCallback callback) {
        this.mCameraCallback = callback;
    }

    public interface CameraCallback {
        void cameraClicked();
    }
}
